import time
import tkinter as tk
from tkinter import filedialog
from openpyxl import Workbook

from auto_ocr_player import OCR_Player

file_paths = ["", ""]


def start_ocr():
    if file_paths[0] == "" or file_paths[1] == "":
        path_label3.config(text="路径设置不全，请确认")
        return

    # OCR文字识别  桌面模式（不能遮挡游戏窗口）
    myplayer = OCR_Player(accuracy=0.6, adb_mode=True, adb_num=0, file_path=file_paths)
    res_list, names = myplayer.find_touch([
        # 发票类型
        # '增值税',
        # '通行费',
        '用发票', '通发票',
        # '统一', '机打',
        # 右上角发票相关
        '发票号码', 'No', 'N',
        '发票代码', '日期', '校验码',
        # 左上角购买方相关
        # '称', '识别号', '电话', '开户行',
        # 中间具体内容
        # '税额', '计', '小写',
        '小写'
        # 左下角销售方相关
        # '称', '识别号', '电话', '开户行'
    ])
    insert_into_excel(res_list, names)


def insert_into_excel(res_list, names=None):
    if len(file_paths) != 2:
        print("Error! 需要指定Excel保存路径")
        return
    work = Workbook()
    sheet = work.active
    sheet['A1'] = '序号'
    sheet['B1'] = '报销人'
    sheet['C1'] = '报销日'
    sheet.column_dimensions['C'].width = 20
    sheet['D1'] = '开票日期'
    sheet.column_dimensions['D'].width = 20
    sheet['E1'] = '大类'
    sheet['F1'] = '开票内容'
    sheet['G1'] = '票种'
    sheet.column_dimensions['G'].width = 20
    sheet['H1'] = '发票号码'
    sheet.column_dimensions['H'].width = 20
    sheet['I1'] = '金额'
    sheet.column_dimensions['I'].width = 20
    sheet['J1'] = '图片名'
    sheet.column_dimensions['J'].width = 25

    current_date = time.strftime("%Y年%m月%d日", time.localtime())
    for idx in range(len(res_list)):
        sheet.append([idx + 1, '', current_date,
                      res_list[idx]['日期'], '', '',
                      res_list[idx]['票种'], res_list[idx]['发票号码'], res_list[idx]['金额'],
                      idx >= len(names) if "" else names[idx]])
    file_name = current_date + '_example.xlsx'
    work.save(file_paths[1] + '\\' + file_name)
    # work.save('example.xlsx')
    print("Excel写入完成...")


def print_inputs():
    if (file_paths[0] != ""
            and file_paths[1] != ""):
        path_label3.config(text="报销单图片文件夹路径:" + file_paths[0]
                                + "\n图片识别Excel保存路径:" + file_paths[1])
    else:
        path_label3.config(text="路径设置不全，请确认")


def select_path1():
    path = filedialog.askdirectory()
    file_paths[0] = path
    # 在第二行打印路径
    path_label1.config(text=path)


def select_path2():
    path = filedialog.askdirectory()
    file_paths[1] = path
    # 在第二行打印路径
    path_label2.config(text=path)


def center_window(window):
    window.update_idletasks()
    width = 400
    height = 300
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    window.geometry(f"{width}x{height}+{x}+{y}")


root = tk.Tk(className="发票批处理demo")
center_window(root)

frame1 = tk.Frame(root)
frame1.pack(pady=30)

# 第1个垂直框架
label1 = tk.Label(frame1, text="报销单图片文件夹路径: ")
label1.grid(row=0, column=0, padx=(0, 100))

button1 = tk.Button(frame1, text="选择路径", command=select_path1)
button1.grid(row=0, column=1)

frame2 = tk.Frame(root)
frame2.pack(pady=10)

path_label1 = tk.Label(frame1)
path_label1.grid(row=1, column=0, columnspan=2)

# 第2个垂直框架
label2 = tk.Label(frame2, text="图片识别Excel保存路径: ")
label2.grid(row=0, column=0, padx=(0, 94))

button2 = tk.Button(frame2, text="选择路径", command=select_path2)
button2.grid(row=0, column=1)

path_label2 = tk.Label(frame2)
path_label2.grid(row=3, column=0, columnspan=2)

# 第3个垂直框架
frame3 = tk.Frame(root)
frame3.pack(pady=10)

button5 = tk.Button(frame3, text="打印路径", command=print_inputs)
button5.grid(row=0, column=0, padx=(0, 195))

button6 = tk.Button(frame3, text="提交", command=start_ocr)
button6.grid(row=0, column=1)

# 第4个垂直框架
frame4 = tk.Frame(root)
frame4.pack(pady=10)
path_label3 = tk.Label(frame4)
path_label3.grid(row=3, column=0, columnspan=2)

root.mainloop()
